//注册和登录路由模块
const path = require('path')
const db = require(path.join(__dirname, '../common/db.js'))
const express = require('express')
const utility = require('utility')
const jwt = require('jsonwebtoken')
const router = express.Router()

//注册
router.post('/reguser', async (req, res) => {
    let params = req.body
    //输入的密码加密
    params.password = utility.md5(params.password)
    //查询数据库中是否已经存在
    let csql = 'select id from user where username = ?'
    let flag = await db.operateDb(csql, params.username)
    if (flag.length > 0) {
        res.json({
            status: 1,
            message: '该用户已存在',
        })
        return
    }
    //信息插入数据库
    let sql = 'insert into user set ?'
    let ret = await db.operateDb(sql, params)
    if (ret.affectedRows > 0) {
        res.json({
            status: 0,
            message: '注册成功',
        })
    } else {
        res.json({
            status: 1,
            message: '注册失败',
        })
    }
})

//登录
router.post('/login', async (req, res) => {
    // 获取用户输入信息
    let params = req.body
    // 密码加密
    params.password = utility.md5(params.password)
    // 查询条件
    let sql = 'select id from user where username = ? and  password = ?'
    let ret = await db.operateDb(sql, [params.username, params.password])
    if (ret.length > 0) {
        let token = jwt.sign({ id: ret[0].id }, 'bigevent', { expiresIn: '2 days' })
        res.json({
            status: 0,
            message: '登录成功',
            token: 'Bearer ' + token
        })
    } else {
        res.json({
            status: 1,
            message: '登录失败',
        })
    }
})

// router.get('/data', async (req, res) => {
//     let sql = 'select * from user where username = ?'
//     let flag = await db.operateDb(csql, params.username)
//     if (flag.length > 0) {
//         res.json({
//             status: 1,
//             message: '该用户已存在',
//         })
//         return
//     }
// })

module.exports = router